// 整合到一个文件当中
(function(window){
  /**
   * @param {String} str 要求第一个字符不为空
   */
  function parseAttrs (str) {
    if (str == undefined) return []

    str += ''

    let isInQuote = false, point = 0

    let ret = []

    for (let i = 0, len = str.length; i < len; ++i) {
      const ch = str[i]

      if (ch == '"') {
        isInQuote = !isInQuote
      } else if (ch == ' ' && !isInQuote) {
        ret.push(str.substring(point, i).trim())
        point = i
      }
    }

    return ret.map(it => {
      const o = it.match(/^(.+)="(.+)"$/)
      return {
        name: o[1],
        value: o[2]
      }
    })
  }


  function parse(templatestr) {
    const startRegExp = /^\<([a-z]+[1-6]?)(\s[^\<]+)?\>/
    const endRegExp = /^\<\/([a-z]+[1-6]?)\>/
    const wdRegExp = /^([^\<]+)/

    let idx = 0
    let rest = ''

    let stk1 = [], stk2 = [{ children: [] }]
    
    while (idx < templatestr.length - 1) {
      rest = templatestr.substr(idx)
      if (startRegExp.test(rest)) {
        let tag = rest.match(startRegExp)[1]
        let attrstr = rest.match(startRegExp)[2]
        
        stk1.push(tag)
        stk2.push({ tag, children: [], attrs: parseAttrs(attrstr?.trim()) })

        const attrsLen = attrstr != undefined ? attrstr.length : 0
        idx += tag.length + 2 + attrsLen
      } else if (endRegExp.test(rest)) {
        let tag = rest.match(endRegExp)[1]
        let pop_tag = stk1.pop()
        
        if (tag == pop_tag) {
          let pop_arr = stk2.pop()
          if (stk2.length > 0) {
            stk2[stk2.length - 1].children.push(pop_arr)
          }
        } else {
          throw new Error('Wrong')
        }

        idx += tag.length + 3
      } else if (wdRegExp.test(rest)) {
        let wd = rest.match(wdRegExp)[1]
        if (!/^\s+$/.test(wd)) {
          stk2[stk2.length - 1].children.push({ text: wd, type: 3 })
        }
        idx += wd.length
      } else {
        idx++
      }
    }
    
    return stk2[0].children[0]
  }

  window.ast = { parse }

})(window)